package com.vhall.component.service.chat.impl;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vhall.component.entity.chat.vo.ChatConsoleListPage;
import com.vhall.component.entity.chat.vo.ChatConsoleListReqVO;
import com.vhall.component.entity.chat.vo.ChatConsoleListRspVO;
import com.vhall.component.entity.export.ExportEntity;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.plugin.common.constant.ConstStr;
import com.vhall.component.plugin.common.constant.HttpConstant;
import com.vhall.component.plugin.common.constant.PaasCommonConstant;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.chat.ChatConsoleService;
import com.vhall.component.service.export.ExportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author guoxin.wang
 * @date 2021/5/28 10:15
 */
@Slf4j
@Service
public class ChatConsoleServiceImpl implements ChatConsoleService {
    @Autowired
    private ExportService exportService;

    @Autowired
    private PaasService paasService;

    private static final String JSON_ARRAY_TYPE_STR = "com.alibaba.fastjson.JSONArray";

    @Override
    public Boolean exportMessage(Integer ilId, Integer accountId, String fileName, String beginTime, String endTime, Integer filterStatus, RoomsEntityDTO roomInfo) {
        ExportEntity ee = new ExportEntity();
        ee.setExport("message");
        ee.setIlId(ilId);
        ee.setAccountId(accountId);
        ee.setFileName(fileName);
        List<String> titles = new ArrayList<>();
        titles.add("直播ID");
        titles.add("直播名称");
        titles.add("昵称");
        titles.add("用户id");
        titles.add("时间");
        titles.add("消息内容");
        ee.setTitle(JSON.toJSONString(titles));
        Map<String, Object> params = new HashMap<>(8);
        params.put("account_id", accountId);
        params.put("il_id", ilId);
        params.put("start_time", beginTime);
        params.put("end_time", endTime);
        params.put("filter_status", filterStatus);
        ee.setParams(JSON.toJSONString(params));
        ee.setExt("csv");
        ee.setCallback("chatService:getMessageExportData");
        ee.setRoomId(roomInfo.getRoomId());
        return exportService.createExport(ee);
    }

    @Override
    public ChatConsoleListPage<ChatConsoleListRspVO> list(ChatConsoleListReqVO reqVO, RoomsEntityDTO roomInfo) {
        List<ChatConsoleListRspVO> result = new ArrayList<>();
        ChatConsoleListRspVO resultOfSingle;
        Integer page = reqVO.getPage();
        Integer pageSize = reqVO.getPageSize();
        String orderBy = "asc";
        // 要查询消息类型，all 为所有
        String type = "text,image";
        String startDate = reqVO.getBeginTime();
        // 消息服务要求精确到时分秒
        if (StringUtils.isNotBlank(startDate)) {
            // 判断格式
            if (startDate.length() == 10) {
                startDate = startDate + " " + ConstStr.TIME_ZERO;
            }
        } else {
            startDate = ConstStr.DATE_TIME_1970;
        }
        String endDate = reqVO.getEndTime();
        if (StringUtils.isNotBlank(endDate)) {
            // 判断格式
            if (endDate.length() == 10) {
                endDate = endDate + " " + ConstStr.TIME_FULL;
            }
        } else {
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
            endDate = sdf.format(now);

        }
        Integer filterStatus = reqVO.getFilterStatus() == null ? 0 : reqVO.getFilterStatus();
        HashMap<String, Object> messageParams = new HashMap<>(16);
        messageParams.put(PaasCommonConstant.CHANNEL_ID_KEY, roomInfo.getChannelId());
        messageParams.put(PaasCommonConstant.CURR_PAGE_KEY, page);
        messageParams.put(PaasCommonConstant.PAGE_SIZE_KEY, pageSize);
        messageParams.put(PaasCommonConstant.MSG_TYPE_KEY, type);
        messageParams.put(PaasCommonConstant.ORDER_BY, orderBy);
        // 0 查询未被阻止的内容， 1 查询被阻止的内容
        messageParams.put("filter_status", filterStatus);
        messageParams.put("audit_status", "all");
        messageParams.put(PaasCommonConstant.START_TIME_KEY, startDate);
        messageParams.put(PaasCommonConstant.END_TIME_KEY, endDate);
        JSONObject resultOfPass = paasService.getMessageLists(messageParams);
        // 看一下这个返回值是不是分页信息。总值在哪里？
        List<JSONObject> results = (List) resultOfPass.getJSONArray("list");
        if (results != null && !results.isEmpty()) {
            for (JSONObject single : results) {
                try {
                    StringBuilder message = new StringBuilder(formatMessage(single));
                    if (single.get("image_urls") != null) {
                        JSONArray arr = (JSONArray) single.get("image_urls");
                        for (int i = 0; i < arr.size(); i++) {
                            message.append(arr.get(i).toString());
                            if (i != arr.size() - 1) {
                                message.append(" ");
                            }
                        }
                    }
                    resultOfSingle = new ChatConsoleListRspVO();
                    resultOfSingle.setAccountId((String) single.get(PaasCommonConstant.THIRD_PARTY_USER_ID_KEY));
                    resultOfSingle.setUsername((String) single.get(PaasCommonConstant.NICK_NAME_KEY));
                    resultOfSingle.setCreatedAt((String) single.get("date_time"));
                    resultOfSingle.setContent(message.toString());
                    result.add(resultOfSingle);
                } catch (Exception e) {
                    log.error("console list error msg {},{}", e.getMessage(), e.getCause());
                    continue;
                }
            }
        }
        Integer pageNum = (Integer) Optional.ofNullable(resultOfPass.get("page_num")).orElse(0);
        Integer total = (Integer) Optional.ofNullable(resultOfPass.get("total")).orElse(0);
        return new ChatConsoleListPage<>(pageNum, reqVO.getPageSize(), total, result);
    }

    private String formatMessage(JSONObject single) {
        String result = "";
        result = (String) single.get(HttpConstant.DATA);
        JSONObject context = (JSONObject) single.get("context");
        String replyMsgKey = "replyMsg";
        String nickNameKey = "nickName";
        if (result.indexOf("***") == 0) {
            result = "@" + result.substring(3);
        } else if (context.get(replyMsgKey) != null) {
            Object replyMsg1 = context.get(replyMsgKey);
            Class<?> aClass = replyMsg1.getClass();
            if (JSON_ARRAY_TYPE_STR.equals(aClass.getName())) {
                JSONArray replyMsg = (JSONArray) context.get(replyMsgKey);
                if (!replyMsg.isEmpty()) {
                    JSONObject o = (JSONObject) replyMsg.get(0);
                    if (o.get(nickNameKey) != null) {
                        result = "回复：" + o.get(nickNameKey) + "：" + result;
                    }
                }
            } else {
                JSONObject replyMsg = (JSONObject) context.get(replyMsgKey);
                if (replyMsg.get(nickNameKey) != null) {
                    result = "回复：" + replyMsg.get(nickNameKey) + "：" + result;
                }
            }
        }
        return result;
    }
}
